#deep seek编写
import os
import time
import keyboard
import pyperclip
import requests
import json
from win32gui import GetForegroundWindow, GetWindowText
import tkinter as tk
from tkinter import messagebox, simpledialog
from threading import Thread
from datetime import datetime

class DoubleClickTranslator:
    def __init__(self):
        # 首先初始化Tkinter根窗口
        self.root = tk.Tk()
        self.root.withdraw()  # 先隐藏主窗口
        
        # 初始化配置
        self.config_file = "translator_config.json"
        self.config = self.load_config()
        
        # 检查API密钥
        self.api_key = self.config.get("api_key", "")
        if not self.api_key:
            self.prompt_for_api_key()
        
        # 如果用户取消了API密钥输入，退出程序
        if not self.api_key:
            messagebox.showerror("错误", "必须提供有效的API密钥才能使用翻译功能")
            self.root.destroy()
            exit()
        
        # 初始化API设置
        self.api_url = "https://api.deepseek.com/v1/chat/completions"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        # 初始化历史记录
        self.history = self.config.get("history", [])
        self.max_history = 20
        
        # 双击检测相关变量
        self.last_ctrl_c_time = 0
        self.double_click_threshold = 0.5
        
        # 配置主窗口
        self.root.deiconify()  # 显示主窗口
        self.root.title("DeepSeek划词翻译 (双击Ctrl+C)")
        self.root.geometry("400x400+100+100")
        self.root.attributes('-topmost', True)
        self.root.attributes('-alpha', 0.6)
        
        # 创建菜单栏
        self.menubar = tk.Menu(self.root)
        self.root.config(menu=self.menubar)
        
        # 添加历史菜单
        history_menu = tk.Menu(self.menubar, tearoff=0)
        history_menu.add_command(label="查看历史", command=self.show_history)
        history_menu.add_command(label="清除历史", command=self.clear_history)
        self.menubar.add_cascade(label="历史记录", menu=history_menu)
        
        # 添加设置菜单
        settings_menu = tk.Menu(self.menubar, tearoff=0)
        settings_menu.add_command(label="更改API密钥", command=self.prompt_for_api_key)
        settings_menu.add_command(label="透明度设置", command=self.set_transparency)
        self.menubar.add_cascade(label="设置", menu=settings_menu)
        
        # 主界面布局
        main_frame = tk.Frame(self.root)
        main_frame.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
        
        # 翻译结果显示区域
        self.text_display = tk.Text(main_frame, wrap=tk.WORD, font=('Microsoft YaHei', 12))
        self.text_display.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)
        self.text_display.config(state=tk.DISABLED)
        
        # 添加滚动条
        scrollbar = tk.Scrollbar(main_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.text_display.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.text_display.yview)
        
        # 状态栏
        self.status_var = tk.StringVar()
        self.status_var.set("就绪 - 双击Ctrl+C翻译选中文本")
        status_bar = tk.Label(self.root, textvariable=self.status_var, bd=1, relief=tk.SUNKEN, anchor=tk.W)
        status_bar.pack(fill=tk.X, padx=5, pady=5)
        
        # 上一次选中的文本
        self.last_selected_text = ""
        
        # 启动快捷键监听
        self.start_hotkey_listener()
        
        # 显示使用说明（仅第一次）
        if not self.config.get("show_instructions", False):
            self.show_instructions()
            self.config["show_instructions"] = True
            self.save_config()
    
    def load_config(self):
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, "r", encoding="utf-8") as f:
                    return json.load(f)
            except:
                return {}
        return {}
    
    def save_config(self):
        """保存配置文件"""
        with open(self.config_file, "w", encoding="utf-8") as f:
            json.dump(self.config, f, ensure_ascii=False, indent=2)
    
    def prompt_for_api_key(self):
        """提示用户输入API密钥"""
        api_key = simpledialog.askstring(
            "API密钥", 
            "请输入DeepSeek API密钥:",
            parent=self.root,
            initialvalue=self.api_key if hasattr(self, 'api_key') and self.api_key else ""
        )
        
        if api_key:
            self.api_key = api_key.strip()
            if hasattr(self, 'headers'):
                self.headers["Authorization"] = f"Bearer {self.api_key}"
            self.config["api_key"] = self.api_key
            self.save_config()
            messagebox.showinfo("成功", "API密钥已更新")
        elif not hasattr(self, 'api_key') or not self.api_key:
            # 如果是在初始化时且没有提供API密钥，返回False表示用户取消了
            return False
        return True
    
    def show_instructions(self):
        """显示使用说明"""
        messagebox.showinfo(
            "使用说明",
            "DeepSeek划词翻译已启动！\n\n"
            "使用方法:\n"
            "1. 在任何程序中选中文本\n"
            "2. 快速双击Ctrl+C(连续按两次)\n"
            "3. 翻译结果将自动显示\n\n"
            "注意: 首次使用时可能需要管理员权限"
        )
    
    def set_transparency(self):
        """设置窗口透明度"""
        transparency = simpledialog.askfloat(
            "透明度设置",
            "请输入透明度值(0.1-1.0):",
            parent=self.root,
            minvalue=0.1,
            maxvalue=1.0,
            initialvalue=self.root.attributes('-alpha')
        )
        
        if transparency:
            self.root.attributes('-alpha', transparency)
    
    def add_to_history(self, original, translation, source):
        """添加到历史记录"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.history.insert(0, {
            "timestamp": timestamp,
            "original": original,
            "translation": translation,
            "source": source
        })
        
        # 限制历史记录数量
        if len(self.history) > self.max_history:
            self.history = self.history[:self.max_history]
        
        # 保存到配置
        self.config["history"] = self.history
        self.save_config()
    
    def show_history(self):
        """显示历史记录窗口"""
        history_window = tk.Toplevel(self.root)
        history_window.title("翻译历史记录")
        history_window.geometry("800x600")
        
        # 添加文本区域
        text_area = tk.Text(history_window, wrap=tk.WORD, font=('Microsoft YaHei', 11))
        text_area.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
        
        # 添加滚动条
        scrollbar = tk.Scrollbar(history_window)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        text_area.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=text_area.yview)
        
        # 填充历史记录
        if not self.history:
            text_area.insert(tk.END, "暂无历史记录")
        else:
            for i, item in enumerate(self.history, 1):
                text_area.insert(tk.END, f"{i}. [{item['timestamp']}] 来自: {item['source']}\n")
                text_area.insert(tk.END, f"原文: {item['original']}\n")
                text_area.insert(tk.END, f"译文: {item['translation']}\n")
                text_area.insert(tk.END, "-"*80 + "\n\n")
        
        text_area.config(state=tk.DISABLED)
    
    def clear_history(self):
        """清除历史记录"""
        if messagebox.askyesno("确认", "确定要清除所有翻译历史记录吗？"):
            self.history = []
            self.config["history"] = []
            self.save_config()
            messagebox.showinfo("成功", "历史记录已清除")
    
    def start_hotkey_listener(self):
        """启动快捷键监听线程"""
        def listen_for_double_ctrl_c():
            keyboard.add_hotkey('ctrl+c', self.check_double_ctrl_c)
        
        listener_thread = Thread(target=listen_for_double_ctrl_c, daemon=True)
        listener_thread.start()
    
    def check_double_ctrl_c(self):
        """检测Ctrl+C双击"""
        current_time = time.time()
        time_since_last = current_time - self.last_ctrl_c_time
        
        if time_since_last < self.double_click_threshold:
            self.last_ctrl_c_time = 0
            self.translate_selected_text()
        else:
            self.last_ctrl_c_time = current_time
    
    def translate_selected_text(self):
        try:
            original_clipboard = pyperclip.paste()
            keyboard.send('ctrl+c')
            time.sleep(0.2)
            selected_text = pyperclip.paste()
            pyperclip.copy(original_clipboard)
            
            if selected_text.strip() and selected_text != self.last_selected_text:
                self.last_selected_text = selected_text
                window_title = GetWindowText(GetForegroundWindow())
                
                self.status_var.set("正在翻译...")
                self.update_display(f"正在翻译来自 '{window_title}' 的文本...\n\n原文:\n{selected_text}")
                
                Thread(target=self.process_translation, args=(selected_text, window_title), daemon=True).start()
                
        except Exception as e:
            self.status_var.set("翻译出错")
            messagebox.showerror("错误", f"翻译过程中出错: {str(e)}")
    
    def process_translation(self, text, window_title):
        """在后台线程中处理翻译"""
        try:
            translation = self.call_deepseek_api(text)
            
            # 添加到历史记录
            self.add_to_history(text, translation, window_title)
            
            self.root.after(0, lambda: self.show_translation_result(text, translation, window_title))
            
        except Exception as e:
            self.root.after(0, lambda: self.show_error(f"翻译处理出错: {str(e)}"))
    
    def call_deepseek_api(self, text):
        """调用DeepSeek API进行翻译"""
        try:
            data = {
                "model": "deepseek-chat",
                "messages": [
                    {
                        "role": "user",
                        "content": f"请将以下内容翻译为中文，保持专业准确，如果是单词给出详细意思（音标+各种意思，不要例句），如果是长句子或段落就只返回译文:\n{text}"
                    }
                ],
                "temperature": 0.3,
                "max_tokens": 2000
            }
            
            response = requests.post(
                self.api_url,
                headers=self.headers,
                json=data,
                timeout=15
            )
            
            response.raise_for_status()
            
            result = response.json()
            translated_text = result.get('choices', [{}])[0].get('message', {}).get('content', '').strip()
            
            return translated_text if translated_text else "未能获取翻译结果"
            
        except requests.exceptions.RequestException as e:
            return f"API请求失败: {str(e)}"
        except Exception as e:
            return f"处理翻译结果时出错: {str(e)}"
    
    def show_translation_result(self, original_text, translation, window_title):
        """显示翻译结果"""
        self.status_var.set("翻译完成")
        self.update_display(
            f"翻译结果 (来自 '{window_title}'):\n\n"
            f"原文:\n{original_text}\n\n"
            f"译文:\n{translation}"
        )
    
    def show_error(self, error_msg):
        """显示错误信息"""
        self.status_var.set("出错")
        messagebox.showerror("错误", error_msg)
    
    def update_display(self, text):
        """更新显示区域内容"""
        self.text_display.config(state=tk.NORMAL)
        self.text_display.delete(1.0, tk.END)
        self.text_display.insert(tk.END, text)
        self.text_display.config(state=tk.DISABLED)
        self.root.deiconify()
    
    def run(self):
        """运行主循环"""
        self.root.mainloop()

if __name__ == "__main__":
    translator = DoubleClickTranslator()
    translator.run()